<template>
  <a-form
      ref="formRef"
      name="dynamic_form_nest_item"
      :model="dynamicValidateForm2"
      @finish="onFinish"
  >
    <a-form-item name="source_process_code"
                 :rules="[{ required: true, message: 'Missing area' }]">
      <a-input v-model:value="dynamicValidateForm2.fromData.source_process_code"/>
    </a-form-item>
    <a-space
        v-for="(user, index) in dynamicValidateForm2.fromData.copy_to"
        :key="user.id"
        style="display: flex; margin-bottom: 8px"
        align="baseline"
    >
      <a-form-item
          :name="['users', index, 'first']"
          :rules="{
          required: true,
          message: 'Missing first name',
        }"
      >
        <a-input v-model:value="user.first" placeholder="First Name"/>
      </a-form-item>
      <a-form-item
          :name="['users', index, 'last']"
          :rules="{
          required: true,
          message: 'Missing last name',
        }"
      >
        <a-input v-model:value="user.last" placeholder="Last Name"/>
      </a-form-item>
      <MinusCircleOutlined @click="removeUser(user)"/>
    </a-space>
    <a-form-item>
      <a-button type="dashed" block @click="addUser">
        <PlusOutlined/>
        Add user
      </a-button>
    </a-form-item>
    <a-form-item>
      <a-button type="primary" html-type="submit">Submit</a-button>
    </a-form-item>
  </a-form>
</template>
<script lang="ts" setup>
import {reactive, ref} from 'vue';
import {MinusCircleOutlined, PlusOutlined} from '@ant-design/icons-vue';
import type {FormInstance} from 'ant-design-vue';

interface User {
  first: string;
  last: string;
  id: number;
}

interface FromData {
  source_process_code: string;
  copy_to: User[];
}

const formRef = ref<FormInstance>();
const dynamicValidateForm = reactive<{ users: User[] }>({
  users: [],
});
const dynamicValidateForm2 = reactive<{ fromData: FromData }>({
  fromData: {
    source_process_code: '',
    copy_to: [{
      first: '',
      last: '',
      id: Date.now(),
    }]
  },
});
const removeUser = (item: User) => {
  const index = dynamicValidateForm2.fromData.copy_to.indexOf(item);
  if (index !== -1) {
    let splice = dynamicValidateForm2.fromData.copy_to.splice(index, 1);
    console.log('splice:', splice);
  }
};
const addUser = () => {
  console.log('Received values of form:', Date.now());
  dynamicValidateForm2.fromData.copy_to.push({
    first: '',
    last: '',
    id: Date.now(),
  });
};
const onFinish = values => {
  console.log('Received values of form:', values);
  console.log('dynamicValidateForm.users:', dynamicValidateForm.users);
};
</script>